"""
微线程，有一些耗时操作才需要这个，例如：网络请求，网络下载（爬虫），文件读写等
"""
import time

import gevent
from greenlet import greenlet

'''
通过生成器实现
'''
# def task1():
#     for i in range(3):
#         print('A'+str(i))
#         yield
#         time.sleep(0.2)
#
# def task2():
#     for i in range(3):
#         print('B'+str(i))
#         yield
#         time.sleep(0.2)
#
# if __name__ == '__main__':
#     g1=task1()
#     g2=task2()
#
#     while True:
#         try:
#             next(g1)
#             next(g2)
#         except:break

'''
通过greenlet包的生成器实现
'''

# def a():
#     for i in range(5):
#         print('A'+str(i))
#         gb.switch()#切换b
#         time.sleep(0.5)
#
# def b():
#     for i in range(5):
#         print('B'+str(i))
#         gc.switch()
#         time.sleep(0.5)
#
# def c():
#     for i in range(5):
#         print('C'+str(i))
#         ga.switch()
#         time.sleep(0.5)
#
# if __name__ == '__main__':
#     ga=greenlet(a)#创建
#     gb=greenlet(b)
#     gc=greenlet(c)
#
#     ga.switch()#执行


'''
通过gevent包可实现自动切换任务，遇到阻塞，有一些耗时操作才需要这个，例如：网络请求，网络下载（爬虫），文件读写等

'''

from gevent import monkey

monkey.patch_all()#补丁，将之后的sleep等耗时操作转换成gevent自带可识别的，则会自动切换

def a():
    for i in range(5):
        print('A'+str(i))
        time.sleep(0.5)

def b():
    for i in range(5):
        print('B'+str(i))
        time.sleep(0.5)

def c():
    for i in range(5):
        print('C'+str(i))
        time.sleep(0.5)

if __name__ == '__main__':
    g1=gevent.spawn(a)#创建
    g2=gevent.spawn(b)
    g3=gevent.spawn(c)

    g1.join()
    g2.join()
    g3.join()